<?php
// +----------------------------------------------------------------------
// | OCR服务层
// +----------------------------------------------------------------------
// | 主要服务于OCR数据处理
// +----------------------------------------------------------------------
// | 错误编码头 248xxx
// +----------------------------------------------------------------------

namespace common\service;

use support\ErrorCode;

class OCRService
{
    /**
     * ocr服务配置
     * @var array
     */
    protected $allowMethod = ['business_license', 'id_card'];

    // ocr服务对象
    protected $apiOcrClient;

    /**
     * 初始化OCR配置
     * OCRService constructor.
     */
    public function __construct()
    {
        $ocrConfig = OptionsService::getInstance()->getOptionsData('ocr_baidu');

        if (empty($ocrConfig) || empty($ocrConfig['app_id']) || empty($ocrConfig['api_key']) || empty($ocrConfig['secret_key'])) {
            throw_strack_exception('OCR configuration does not exist.', ErrorCode::OCR_CONFIG_NOT_EXIST);
        }

        $this->apiOcrClient = new \AipOcr($ocrConfig['app_id'], $ocrConfig['api_key'], $ocrConfig['secret_key']);
    }


    /**
     * 获取图片内容
     * @param string $img
     * @return false|string
     */
    protected function getImageContent($img = '')
    {
        //如果是本地文件
        if ((strpos($img, 'http') === false && strpos($img, 'https') === false) && !file_exists($img)) {
            throw_strack_exception('The picture does not exist.', ErrorCode::PICTURE_NOT_EXIST);
        }
        //获取文件内容
        $fileContent = file_get_contents($img);
        if ($fileContent === false) {
            return $img;
        }

        return $fileContent;
    }

    /**
     * 格式化营业执照数据
     * @param $data
     * @return array
     */
    protected function formatBusinessLicenseData($data)
    {
        return [
            'company_name' => [
                'filed' => 'company_name',
                'text' => '公司名称',
                'value' => $data['单位名称']['words'] ?? ''
            ],
            'company_type' => [
                'filed' => 'company_type',
                'text' => '公司类型',
                'value' => $data['类型']['words'] ?? ''
            ],
            'legal_person_name' => [
                'filed' => 'legal_person_name',
                'text' => '法人',
                'value' => $data['法人']['words'] ?? ''
            ],
            'registered_capital' => [
                'filed' => 'legal_person_name',
                'text' => '注册资本',
                'value' => $data['注册资本']['words'] ?? ''
            ],
            'unified_social_credit_code' => [
                'filed' => 'unified_social_credit_code',
                'text' => '统一社会信用代码',
                'value' => $data['社会信用代码']['words'] ?? ''
            ],
            'company_registered_address' => [
                'filed' => 'company_registered_address',
                'text' => '公司注册地址',
                'value' => $data['地址']['words'] ?? ''
            ],
            'company_business_scope' => [
                'filed' => 'company_business_scope',
                'text' => '公司经营范围',
                'value' => $data['经营范围']['words'] ?? ''
            ],
            'operation_period_end' => [
                'filed' => 'operation_period_end',
                'text' => '经营期限(止)',
                'value' => $data['有效期']['words'] ?? ''
            ]
        ];
    }


    /**
     * 格式化身份证正面数据
     * @param $data
     * @param $type
     * @return array
     */
    protected function formatIdCardData($data, $type)
    {
        if ($type === 'front') {
            // 正面数据
            return [
                'legal_person_name' => [
                    'filed' => 'legal_person_name',
                    'text' => '姓名',
                    'value' => $data['姓名']['words'] ?? ''
                ],
                'legal_person_nation' => [
                    'filed' => 'legal_person_nation',
                    'text' => '民族',
                    'value' => $data['民族']['words'] ?? ''
                ],
                'legal_person_home_address' => [
                    'filed' => 'legal_person_home_address',
                    'text' => '家庭住址',
                    'value' => $data['住址']['words'] ?? ''
                ],
                'legal_id_number' => [
                    'filed' => 'legal_id_number',
                    'text' => '身份号码',
                    'value' => $data['公民身份号码']['words'] ?? ''
                ],
                'legal_id_birthday' => [
                    'filed' => 'legal_id_birthday',
                    'text' => '生日',
                    'value' => $data['出生']['words'] ?? ''
                ],
                'legal_id_sex' => [
                    'filed' => 'legal_id_birthday',
                    'text' => '性别',
                    'value' => $data['性别']['words'] ?? ''
                ]
            ];
        } else {
            return [
                'legal_id_period_end' => [
                    'filed' => 'legal_id_period_end',
                    'text' => '失效日期',
                    'value' => $data['失效日期']['words'] ?? ''
                ],
                'legal_signed_organization' => [
                    'filed' => 'legal_signed_organization',
                    'text' => '签发机关',
                    'value' => $data['签发机关']['words'] ?? ''
                ],
                'legal_issue_date' => [
                    'filed' => 'legal_issue_date',
                    'text' => '签发日期',
                    'value' => $data['签发日期']['words'] ?? ''
                ]
            ];
        }
    }

    /**
     * 解析图片
     * @param $param
     * @return array
     */
    public function parse($param)
    {
        if (in_array($param['type'], $this->allowMethod)) {
            $imageBase64 = $this->getImageContent($param['url']);
            switch ($param['type']) {
                case 'business_license':
                    // 营业执照
                    $businessLicenseParam = $this->apiOcrClient->businessLicense($imageBase64);
                    if (array_key_exists('error_code', $businessLicenseParam)) {
                        throw_strack_exception($businessLicenseParam['error_code'] . ' : ' . $businessLicenseParam['error_msg'], ErrorCode::BUSINESS_LICENSE_ERROR);
                    }

                    return $this->formatBusinessLicenseData($businessLicenseParam['words_result']);
                    break;
                case 'id_card':
                    // 身份证
                    $idCardParam = $this->apiOcrClient->idcard($imageBase64, $param['id_card_side']);

                    if (array_key_exists('error_code', $idCardParam)) {
                        throw_strack_exception($idCardParam['error_code'] . ' : ' . $idCardParam['error_msg'], ErrorCode::ID_CARD_ERROR);
                    }

                    return $this->formatIdCardData($idCardParam['words_result'], $param['id_card_side']);
                    break;
            }
        } else {
            $methodStr = join(',', $this->allowMethod);
            throw_strack_exception("Currently only supported method : {$methodStr}", ErrorCode::METHOD_NOT_SUPPORTED);
        }
    }
}
